package com.choosefine.it.base;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.choosefine.it.mobile.equipment.dto.ShoppingIdentityDTO;
import com.choosefine.it.base.dto.DateDTO;
import com.choosefine.it.base.dto.IdentityDTO;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.json.JsonResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;

/**
 * 控制层的共性
 * 
 * @auth liaozhanggen 2016-11-19 上午9:42:30
 * 
 */
public class BaseController {

	private Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	@Value("#{yaml.get('service.shixiaobao.url')}")
	public String shixiaobaoURL;

	@Value("#{yaml.get('service.shopping.url')}")
	public String shoppingURL;

	@Value("#{yaml.get('service.usercent.url')}")
	public String usercentURL;

	@Value("#{yaml.get('service.push.url')}")
	public String pushURL;
	
	protected final static String DATE_FORMATE = "yyyy-MM-dd";
	private JsonResult result = null;

	/**
	 * @param data
	 *            返回的展示数据 json 对象
	 * @param MESSAGE
	 *            返回的成功或失败的原因 比如：SUCCESS / ERROR ....
	 * @param resultCode
	 *            返回的成功或失败的编码 比如：200、 500、400....
	 * 
	 * @auth liaozhanggen 2016-11-19 上午10:14:42
	 */
	public JsonResult responseSuccess(Object data, String MESSAGE, Integer resultCode) {
		logger.info("--------------getInstanceJsonResult--------------> new");
		result = new JsonResult(data, MESSAGE, resultCode);
		return result;
	}
	
	public String responseSuccess() {
		this.responseSuccess(null,ResultCode.MSG_SUCCESS, ResultCode.SUCCESS);
		return result.toJson();
	}

	public String responseSuccess(Object data) {
		logger.info("后端返回对象：{}", data);
		if (data instanceof Page){
			Map<String,Object> param = new HashMap<>();
			param.put(CommonConstant.ARRAY,data);
			param.put(CommonConstant.PAGE_COUNT,((Page)data).toPageInfo().getPages());//总页数
			param.put(CommonConstant.TOTAL,((Page)data).toPageInfo().getTotal()); //总条数
			data = param;
		}
		this.responseSuccess(data, ResultCode.MSG_SUCCESS, ResultCode.SUCCESS);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}
	public String responseSuccess(Object data, String MESSAGE) {
		logger.info("后端返回对象：{}", data);
		result = new JsonResult(data, MESSAGE, ResultCode.SUCCESS);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseSuccess(Object data, Integer resultCode, String MESSAGE) {
		logger.info("后端返回对象：{}", data);
		result = new JsonResult(data, MESSAGE, resultCode);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseArraySuccess(PageInfo<?> arraydata) {
		logger.info("后端返回对象：{}", arraydata);
		result = new JsonResult(arraydata, ResultCode.MSG_QUERY_SUCCESS, ResultCode.SUCCESS);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseArraySuccess(List<?> arraydata) {
		logger.info("后端返回对象：{}", arraydata);
		result = new JsonResult(arraydata, ResultCode.MSG_QUERY_SUCCESS, ResultCode.SUCCESS);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseArraySuccess(List<?> data, Integer resultCode, String MESSAGE) {
		logger.info("后端返回对象：{}", data);
		result = new JsonResult(data, MESSAGE, resultCode);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseFail() {
		result = new JsonResult(ResultCode.MSG_ERROR,ResultCode.FAILED);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseCreateFail() {
		result = new JsonResult(ResultCode.MSG_CREATE_ERROR,ResultCode.FAILED);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseUpdateFail() {
		result = new JsonResult(ResultCode.MSG_UPDATE_ERROR,ResultCode.FAILED);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseDeleteFail() {
		result = new JsonResult(ResultCode.MSG_DELETE_FAILD,ResultCode.FAILED);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseFail(String MESSAGE) {
		result = new JsonResult(MESSAGE, ResultCode.FAILED);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseFail(Integer resultCode, String MESSAGE) {
		result = new JsonResult(MESSAGE, resultCode);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}
	public String responseDataFail(Object data) {
		logger.info("后端返回对象：{}", data);
		result = new JsonResult(data, "FAILD", ResultCode.FAILED);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	/**
	 * 11.29dzq 用于输入时间判断。
	 * 
	 * @return 返回时间是否合法
	 */
	public boolean timeJudge(Long startTime, Long endTime) {
		if (startTime == 0 && endTime == 0) {
			endTime = System.currentTimeMillis();
		}
		if (endTime == 0) {// 如果结束时间为0
			endTime = System.currentTimeMillis();// 取当前时间
		}
		if (startTime >= endTime || startTime < 0)
			return false;
		return true;
	}

	/**
	 * 12.7 dzq 时间验证，需配合datedto
	 * 
	 * @return
	 */
	public boolean timeJudge(DateDTO date) {
		if (date == null) {
			return false;
		}
		if (date.getStartTime() == 0 && date.getEndTime() == 0) {
			date.setEndTime(System.currentTimeMillis());
		}
		if (date.getEndTime() == 0) {// 如果结束时间为0
			date.setEndTime(System.currentTimeMillis());// 取当前时间
		}
		if (date.getStartTime() >= date.getEndTime() || date.getStartTime() < 0)
			return false;
		return true;
	}

	/**
	 * 请求身份验证
	 * 
	 * @param identity
	 * @return
	 */
	public boolean identityVerification(ShoppingIdentityDTO identity) {
		if (identity == null) {
			return false;
		}
		if ((identity.getTeamId() == null || "".equals(identity.getTeamId()))
				&& (identity.getProjectCode() == null || "".equals(identity.getProjectCode()))
				&& (identity.getUserCode() == null || "".equals(identity.getUserCode()))) {
			return false;
		}
		return true;
	}

	/**
	 * 参数map添加用户与时间
	 * 
	 * @param map
	 * @param date
	 * @param identity
	 */
	public Map<String, Object> fomartMap(Map<String, Object> map, DateDTO date, ShoppingIdentityDTO identity) {
		if (map == null)
			map = new HashMap<String, Object>();
		Iterator<String> ite = map.keySet().iterator();
		while (ite.hasNext()) {
			Object now = ite.next();
			if ("-1".equals(map.get(now.toString()).toString())) {
				map.remove(now.toString());
			}
		}
		if (identity != null) {// 身份
			map.put("userCode", identity.getUserCode());
			map.put("projectCode", identity.getProjectCode());
			map.put("teamId", identity.getTeamId());
		}
		if (date != null) {
			map.put("startTime", date.getStartTime());
			map.put("endTime", date.getEndTime());
		}
		return map;
	}
	/**
	 * 请求身份验证
	 * @param identity
	 * @return
	 */
	public boolean identityVerification(IdentityDTO identity){
		if(identity==null){
			return false;
		}
		if((identity.getTeamId()==null||"".equals(identity.getTeamId()))
				&&(identity.getProjectCode()==null||"".equals(identity.getProjectCode()))
				&&(identity.getUserCode()==null||"".equals(identity.getUserCode()))){
			return false;
		}
		return true;
	}
	
	/**
	 * 参数map添加用户与时间
	 * @param map
	 * @param date
	 * @param identity
	 */
	public Map<String, Object> fomartMap(Map<String, Object> map,DateDTO date,IdentityDTO identity){
		if(map==null)
			map=new HashMap<String, Object>();
		Iterator<String> ite=map.keySet().iterator();
		while(ite.hasNext()){
			Object now=ite.next();
			if("-1".equals(map.get(now.toString()).toString())){
				map.remove(now.toString());
			}
		}
		if(identity !=null){//身份
			map.put("userCode", identity.getUserCode());
			map.put("projectCode", identity.getProjectCode());
			map.put("teamId", identity.getTeamId());
		}
		if(date !=null){
			map.put("startTime",date.getStartTime() );
			map.put("endTime", date.getEndTime());
		}
		return map;
	}
	/**
	 * 12.13dzq 增加时间方法，为前端提供当前页面可选时间段
	 * 
	 * @return
	 */
	@Deprecated
	public static List<String> timeList(long startTime, long endTime, List<String> list) {
		if (list == null)
			list = new ArrayList<String>();
		SimpleDateFormat sf = new SimpleDateFormat(" ");
		int n = 0;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTimeInMillis(startTime);
		c2.setTimeInMillis(endTime == 0 ? System.currentTimeMillis() : endTime);
		while (!c1.after(c2)) {
			if (n == 0) {
				list.add(sf.format(c1.getTime()));
			} else {
				c1.add(Calendar.MONTH, 1);
				list.add(sf.format(c1.getTime()));
			}
			n++;
		}
		list.remove(n - 1);
		return list;
	}
}
